<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of home
 *
 * @author Gidaff_01
 */
class Home extends Doggy_Flirt_FrontEnd_Controller {

    //put your code here
    function Home() {
        parent::Doggy_Flirt_FrontEnd_Controller();
        $this->load->model('Home_m');
        $this->load->model('image/Image_m');
        $this->load->helper('date');
        $this->_data['erreur'] = "";
        $this->load->library('email');
    }

    function index() {
        //$this->display_view('home/index');
        $this->nouveaux_membres();
    }

    function compte($id) {
        $this->_data['accounts'] = $this->Home_m->get_account_details($id);
        $this->_data['recent_images'] = $this->Image_m->get_recent_images($id, 4);
        $per_page = $this->uri->segment(4) != '' ? $this->uri->segment(4) : 10;
        $off_set = $this->uri->segment(5) != '' ? $this->uri->segment(5) : 0;
        $config['base_url'] = base_url() . 'index.php/home/compte/' . '/' . $id . '/' . $per_page . '/';
        $config['per_page'] = $per_page;
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->Home_m->count_all_message($id);
        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['own_walls'] = $this->Home_m->get_own_walls($id, $per_page, $off_set);
        $this->_data['not_friend'] = $this->Friend_m->check_not_friend($id, $this->_data['account_id']);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->display_view('home/compte');
    }

    function wall_friend($id) {
        $this->_data['accounts'] = $this->Home_m->get_account_details($id);
        $this->_data['recent_images'] = $this->Image_m->get_recent_images($id, 4);
        $per_page = $this->uri->segment(4) != '' ? $this->uri->segment(4) : 10;
        $off_set = $this->uri->segment(5) != '' ? $this->uri->segment(5) : 0;
        $config['base_url'] = base_url() . 'index.php/home/wall_friend/' . '/' . $id . '/' . $per_page . '/';
        $config['per_page'] = $per_page;
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->Home_m->count_all_message($id);
        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['own_walls'] = $this->Home_m->get_own_walls($id, $per_page, $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->display_view('home/wall_friend');
    }

    function galery_friend($id) {
        $this->_data['accounts'] = $this->Home_m->get_account_details($id);

        $per_page = $this->uri->segment(4) != '' ? $this->uri->segment(4) : 10;
        $off_set = $this->uri->segment(5) != '' ? $this->uri->segment(5) : 0;
        $config['base_url'] = base_url() . 'index.php/home/galery_friend/' . '/' . $id . '/' . $per_page . '/';
        $config['per_page'] = $per_page;
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->Image_m->count_all_images($id);

        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['recent_images'] = $this->Image_m->get_my_galary($id, $per_page, $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();

        $this->display_view('home/galery_friend');
    }

    function nouveaux_membres() {
        $per_page = $this->uri->segment(3) != '' ? $this->uri->segment(3) : 20;
        $off_set = $this->uri->segment(4) != '' ? $this->uri->segment(4) : 0;
        $config['base_url'] = base_url() . 'index.php/home/nouveaux_membres/' . '/' . $per_page . '/';
        $config['per_page'] = $per_page;
        $config['uri_segment'] = 4;
        $config['total_rows'] = $this->db->count_all('doggy_accounts');
        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['new_members'] = $this->Home_m->get_random_member($per_page, $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->display_view('home/index');
    }

    function doggy_area() {
        $this->display_view('home/doggy_area');
    }

    function register() {
        /* Captcha */
        $expiration_period = time() - 1800;
        $this->db->query("DELETE FROM captcha WHERE captcha_time < " . $expiration_period);
        $this->load->plugin('captcha');
        $vals = array(
            'word' => strtoupper(random_string('alnum', 6)),
            'img_path' => './assets/captcha/',
            'img_url' => base_url() . 'assets/captcha/',
            'font_path' => base_url() . 'system/fonts/texb.ttf',
            'img_width' => '150',
            'img_height' => 32,
            'expiration' => 300
        );

        $cap = create_captcha($vals);

        $cap_save = array(
            'captcha_id' => '',
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']
        );
        $query = $this->db->insert_string('captcha', $cap_save);
        $this->db->query($query);
        $this->_data['captcha_img'] = $cap['image'];
        /* End of captcha */
        if ($this->input->post('register')) {
            $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
            $dob_long = human_to_unix($birthday);
            if($dob_long>now()){
                $this->_data['date_erreur']='Sélection de date non valide';    
            }
            $this->_data['selected_day'] = $this->input->post('birth_date'); 
            $this->_data['selected_month'] = $this->input->post('birth_month'); 
            $this->_data['selected_year'] = $this->input->post('birth_year'); 
            $formVal = array(
                array(
                    'field' => 'account_name',
                    'Label' => 'Account name',
                    'rules' => 'required|callback_check_exist_account|max_length[20]'
                ),
                array(
                    'field' => 'fullname',
                    'Label' => 'fullname',
                    'rules' => 'required'
                ),
                array(
                    'field' => 'display_name',
                    'Label' => 'display_name',
                    'rules' => 'required|max_length[20]'
                ),
                array(
                    'field' => 'email',
                    'Label' => 'email',
                    'rules' => 'required|valid_email|callback_check_exist_email'
                ),
                array(
                    'field' => 'password',
                    'Label' => 'Password',
                    'rules' => 'required|matches[confirm_password]|min_length[5]'
                ),
                array(
                    'field' => 'confirm_password',
                    'Label' => 'Confirm Password',
                    'rules' => 'required'
                ),
                array(
                    'field' => 'captcha',
                    'Label' => 'Picture letters',
                    'rules' => 'required|max_length[6]|callback_is_correct_captcha'
                )
            );
            $this->form_validation->set_rules($formVal);
            if ($this->form_validation->run() === TRUE&&$dob_long<now()) {
                $account_name = $this->input->post('account_name');
                $password = $this->input->post('password');
                $data_user = array('id' => time(),
                    'account_name' => $account_name,
                    'email' => $this->input->post('email'),
                    'pass' => md5($password),
                    'race' => $this->input->post('race'),
                    'region' => $this->input->post('region')
                );
                $this->Home_m->register_account($data_user);

                $query_id_max = $this->Home_m->get_account_id_max();
                $user = $query_id_max->row();
                $user_id = $user->new_id;
                $data_profile = array('account_id' => $user_id,
                    'fullname' => ucwords(strtolower($this->input->post('fullname'))),
                    'birthday' => $dob_long,
                    'display_name' => ucwords(strtolower($this->input->post('display_name'))),
                    'sex' => $this->input->post('gender')
                );
                $this->Home_m->register_profile($data_profile);

                $query = $this->Home_m->login($account_name, md5($password));
                $row = $query->row();
                $self = array(
                    'account_id' => $row->id,
                    'friend_id' => $row->id
                );
                $this->Friend_m->add_friend($self);
                $this->session->set_userdata('doogy.id', $row->id);
                $this->session->set_userdata('account_name', $row->account_name);
                 $this->session->set_userdata('doggy_display_name', ucwords(strtolower($this->input->post('display_name'))));
                $this->_data['doggy_display_name']=$this->input->post('display_name');
                $this->session->set_userdata('avatar', NULL);
                $this->session->set_flashdata('msg', "Inscrivez-succès! Maintenant, S'il vous plaît modifier votre profil");

                //send mail
                $this->email->from('administrator@lehu.com', 'Doggy-flirt');
                $this->email->to($this->input->post('email'));
                $this->email->subject('Inscrivez-succès');
                $message = 'Hello ' . $row->account_name . 'Merci de vous enregistrer avec Doggy-flirt. Bienvenue!';
                $this->email->message($message);
                $this->email->send();
                redirect(site_url());
                //end send mail
                redirect('home/edit_profile' . '/' . $row->id);
            } else {
                $this->display_view('home/register');
            }
        } else {
            $this->display_view('home/register');
        }
    }

    function is_correct_captcha($captcha) {
        $expiration = time() - 1800;
        $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
        $binds = array($captcha, $this->input->ip_address(), $expiration);
        $query = $this->db->query($sql, $binds);
        $row = $query->row();

        if ($row->count == 0) {
            $this->form_validation->set_message('is_correct_captcha', 'Please enter correct word in the picture!');
            return FALSE;
        }
        return TRUE;
    }

    function check_exist_account() {
        $account_name = $this->input->post('account_name');
        $query = $this->Home_m->get_exist_account($account_name);
        if ($query->num_rows() > 0) {
            $this->form_validation->set_message('check_exist_account', 'The account name was exist');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function check_exist_email() {
        $email = $this->input->post('email');
        $query = $this->Home_m->get_exist_email($email);
        if ($query->num_rows() > 0) {
            $this->form_validation->set_message('check_exist_email', 'The email was exist');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function login() {
        $config = array(
            array(
                'field' => 'account_name_login',
                'label' => 'Account name',
                'rules' => 'required'
            ),
            array(
                'field' => 'pass',
                'label' => 'password',
                'rules' => 'required'
            )
        );
        $this->form_validation->set_rules($config);
        $account_name = $this->input->post('account_name_login');
        $pass = md5($this->input->post('pass'));
        if ($this->input->post('submit')) {
            if ($this->form_validation->run()) {
                $query = $this->Home_m->login($account_name, $pass);
                if ($query->num_rows() > 0) {
                    $row = $query->row();
                    $this->session->set_userdata('doogy.id', $row->id);
                    $this->session->set_userdata('account_name', $row->account_name);
                    $this->session->set_userdata('doggy_display_name', $row->display_name);
                    $this->session->set_userdata('avatar', $row->avatar);
                    redirect('home/show_wall_message');
                } else {
                    $this->_data['erreur'] = "Identifiant ou mot de passe n'existe pas";
                    $this->display_view('home/index');
                }
            } else {
                $this->_data['validate_erreur'] = TRUE;
                $this->display_view('home/index');
            }
        } else {
            $this->display_view('home/index');
        }
    }

    function forgot_pass() {
        //echo random_string('alnum', 16);die;
        $config = array(
            array(
                'field' => 'email',
                'label' => 'Your email',
                'rules' => 'required|valid_email'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->input->post('submit')) {
            if ($this->form_validation->run()) {
                $temp_pass = random_string('alnum', 16);
                $email = $this->input->post('email');
                $account_info = $this->Home_m->get_account_infor_by_email($email);
                if ($account_info->num_rows() > 0) {
                    $account = $account_info->row();
                    $data = array(
                        'pass' => md5($temp_pass)
                    );
                    if ($this->Home_m->update_temp_pass($email, $data) > 0) {
                        $this->email->from('administrator@lehu.com', 'Doggy-flirt');
                        $this->email->to($email);
                        $this->email->subject('Mot de passe de récupération');
                        $message = 'Hello ' . $account->account_name . ' please use following account and temporary pass to login at lehu:  user: ' . $account->account_name . ' temporary pass: ' . $temp_pass;
                        $this->email->message($message);
                        $this->email->send();
                        redirect(site_url());
                    }
                } else {
                    $this->_data['error'] = "votre e-mail n'a pas été enregistré";
                    $this->display_view('home/forgot_pass');
                }
            } else {
                $this->display_view('home/forgot_pass');
            }
        } else {
            $this->display_view('home/forgot_pass');
        }
    }

    function logout() {
        $this->session->unset_userdata('doogy.id');
        $this->session->unset_userdata('account_name');
        redirect(base_url());
    }

    function edit_profile($id=0) {
        is_user();
        $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
        $dob_long = human_to_unix($birthday);
        $account = $this->Home_m->get_account_details($id);
        $this->_data['account_data'] = $account;

        $this->_data['erreur'] = "";
        $config = array(
            array(
                'field' => 'display_name',
                'label' => 'Display name',
                'rules' => 'required|max_length[20]'
            ),
            array(
                'field' => 'fullname',
                'label' => 'Fullname',
                'rules' => 'required'
            ),
            array(
                'field' => 'color',
                'label' => 'Color',
                'rules' => 'required'
            ),
            array(
                'field' => 'address',
                'label' => 'Address',
                'rules' => 'required'
            ),
            array(
                'field' => 'race',
                'label' => 'Race',
                'rules' => 'required'
            ),
            array(
                    'field' => 'display_name',
                    'Label' => 'Display name',
                    'rules' => 'required|max_length[25]'
            ),
            array(
                'field' => 'region',
                'Label' => 'Region',
                'rules' => 'required'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->input->post('submit')) {
            $image_path = './doggy_avatar';
            $thumb_path = $image_path . '/images';
            $config = array(
                'allowed_types' => "jpg|jpeg|gif|png",
                'upload_path' => $image_path,
                'max_size' => 10000,
                'encrypt_name' => TRUE
            );
            $this->_data['page_title'] = "Uploading...";
            $this->load->library('upload', $config);

            if ($this->upload->do_upload()) {
                $upload_info = $this->upload->data();
                $config = array(
                    'source_image' => $upload_info['full_path'], //get original image
                    'new_image' => $thumb_path, //save as new image //need to create thumbs first
                    'maintain_ratio' => true,
                    'width' => 300,
                    'height' => 200
                );
                $this->load->library('image_lib', $config); //load library
                $this->image_lib->resize(); //do whatever specified in config
                delete_pro_file($upload_info['full_path']);

                if ($this->form_validation->run()) {
                    $data_account = array(
                        'race' => $this->input->post('race'),
                        'region' => $this->input->post('region')
                    );
                    $this->Home_m->edit_account($data_account, $id);
                    $data = array(
                        'display_name' => $this->input->post('display_name'),
                        'fullname' => $this->input->post('fullname'),
                        'color' => $this->input->post('color'),
                        'address' => $this->input->post('address'),
                        'sex' => $this->input->post('gender'),
                        'birthday' => $dob_long,
                        'avatar' => $upload_info['file_name']
                    );
                    $this->Home_m->edit_profile($data, $id);
                    $this->session->set_userdata('avatar', $upload_info['file_name']);
                    $this->_data['doggy_display_name']=$this->input->post('display_name');
                    redirect('home/show_wall_message');
                } else {
                    $this->display_view('home/edit_profile');
                }
            } else {
                if ($this->form_validation->run()) {
                    $data_account = array(
                        'race' => $this->input->post('race'),
                        'region' => $this->input->post('region')
                    );
                    $this->Home_m->edit_account($data_account, $id);
                    $data = array(
                        'display_name' => $this->input->post('display_name'),
                        'fullname' => $this->input->post('fullname'),
                        'color' => $this->input->post('color'),
                        'address' => $this->input->post('address'),
                        'sex' => $this->input->post('gender'),
                        'birthday' => $dob_long
                            //'avatar' => $upload_info['file_name']
                    );
                    $this->Home_m->edit_profile($data, $id);
                    redirect('home/show_wall_message');
                } else {
                    $this->display_view('home/edit_profile');
                }
            }
        } else {
            $this->display_view('home/edit_profile');
        }
    }

    function change_pass($id) {
        is_user();
        $adminid = $this->session->userdata('doogy.id');
        $this->_data['erreur'] = "";

        $config = array(
            array(
                'field' => 'apass',
                'label' => 'Ancien mot de passe',
                'rules' => 'required|md5'
            ),
            array(
                'field' => 'npass',
                'label' => 'Nouveau mot de passe',
                'rules' => 'required|matches[confirm_npass]|md5'
            ),
            array(
                'field' => 'confirm_npass',
                'label' => 'Confirmation du mot de passe',
                'rules' => 'required|md5'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->form_validation->run()) {
            $pass = $this->input->post('apass');
            $query = $this->Home_m->is_password($pass, $adminid);
            if ($query) {
                $data = array('pass' => $this->input->post('npass'));
                $query = $this->Home_m->change_pass($data, $adminid);
                redirect('home/index');
            } else {
                $this->_data['erreur'] = "Mot de passe incorrect";
                $this->display_view('home/change_pass');
            }
        }else
            $this->display_view('home/change_pass');
    }

    function show_wall_message($post_to=0) {
        is_user();
        $per_page = $this->uri->segment(3) != '' ? $this->uri->segment(4) : 10;
        $off_set = $this->uri->segment(4) != '' ? $this->uri->segment(5) : 0;
        $config['base_url'] = base_url() . 'index.php/home/show_wall_message/' . $post_to . '/' . $per_page . '/';
        $config['per_page'] = $per_page;
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->Home_m->count_wall_messages($this->_data['account_id'], $post_to);
        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['wall_messages'] = $this->Home_m->show_wall_message($this->_data['account_id'], $post_to, $per_page, $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();

        $this->display_view('home/doggy_area');
    }

    function search() {
        $sex = $this->input->post('sex') != '' ? $this->input->post('sex') : '_';
        $race = $this->input->post('race') != '' ? $this->input->post('race') : '_';
        $region = $this->input->post('region') != '' ? $this->input->post('region') : '_';

        $account_id = $this->_data['account_id'];
        $this->_data['selected_sex'] = $sex;
        $this->_data['selected_race'] = $race;
        $this->_data['selected_region'] = $region;
        $per_page = 20;
        $config['per_page'] = $per_page;
        $config['uri_segment'] = 8;
        $config['total_rows'] = $this->Home_m->count_search($account_id, $sex, $race, $region);
        $this->_data['search_result'] = $this->Home_m->search($account_id, $sex, $race, $region, $per_page, 0);
        $config['base_url'] = site_url('home/pagination_search') . '/' . $account_id . '/' . $sex . '/' . $race . '/' . $region . '/' . $per_page . '/';
        $this->_data['total'] = $this->Home_m->count_search($account_id, $sex, $race, $region);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();

        $this->display_view('home/search_result');
    }

    function pagination_search($account_id, $sex, $race, $region, $per_page) {
        $this->_data['selected_sex'] = $sex;
        $this->_data['selected_race'] = $race;
        $this->_data['selected_region'] = $region;
        $off_set = $this->uri->segment(8);
        if ($off_set == FALSE)
            $offset = 0;
        $config['per_page'] = $per_page;
        $config['uri_segment'] = 8;
        $config['total_rows'] = $this->Home_m->count_search($account_id, $sex, $race, $region);
        $this->_data['search_result'] = $this->Home_m->search($account_id, $sex, $race, $region, $per_page, $off_set);
        $config['base_url'] = site_url('home/pagination_search') . '/' . $account_id . '/' . $sex . '/' . $race . '/' . $region . '/' . $per_page . '/';
        $this->_data['total'] = $this->Home_m->count_search($account_id, $sex, $race, $region);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->display_view('home/search_result');
    }

    function delete_wall_message($message_id, $id, $flag=0) {
        $query = $this->Home_m->get_images_message_by_id($message_id);
        if ($query->num_rows() > 0) {
            $row = $query->row();
            $file_name = './upload_photo/thumbs/' . $row->image;
            $file_name_full = './upload_photo/' . $row->image;
            if ($row->image != NULL) {
                delete_pro_file($file_name);
                delete_pro_file($file_name_full);
            }
        }
        $this->Home_m->delete_wall_message($message_id);
        if ($flag == 0) {
            redirect('home/wall_friend' . '/' . $id);
        } else {
            redirect('home/show_wall_message');
        }
    }

}

?>
